package com.kjsdfgk.hjmdsf.livev3.mvp.ui.activity;

import android.view.ViewGroup;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.fragment.app.FragmentTransaction;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class PagerFragmentStatePager extends FragmentStatePagerAdapter {

        List<Fragment> listFragments = new ArrayList<>();
        FragmentManager fragmentManager;


        public void setListFragments(List<Fragment> listFragments) {
            this.listFragments = listFragments;
        }

        public PagerFragmentStatePager(FragmentManager fm) {
            super(fm);
            this.fragmentManager=fm;
        }

        @Override
        public Fragment getItem(int position) {
            return listFragments.get(position);
        }

        @Override
        public int getCount() {
            return listFragments.size();
        }

        @Override
        public int getItemPosition(Object object) {
            // TODO Auto-generated method stub
            return POSITION_NONE;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // TODO Auto-generated method stub
//            if (position == 0)
//                removeFragment(container,position);
            return super.instantiateItem(container, position);
        }

        private void removeFragment(ViewGroup container,int index) {
            String tag = getFragmentTag(container.getId(), index);
            Fragment fragment = fragmentManager.findFragmentByTag(tag);
            if (fragment == null)
                return;
            FragmentTransaction ft = fragmentManager.beginTransaction();
            ft.remove(fragment);
            ft.commitAllowingStateLoss();
            ft = null;
            fragmentManager.executePendingTransactions();
        }

        private String getFragmentTag(int viewId, int index) {
            try {
                Class<FragmentPagerAdapter> cls = FragmentPagerAdapter.class;
                Class<?>[] parameterTypes = { int.class, long.class };
                Method method = cls.getDeclaredMethod("makeFragmentName",
                        parameterTypes);
                method.setAccessible(true);
                String tag = (String) method.invoke(this, viewId, index);
                return tag;
            } catch (Exception e) {
                e.printStackTrace();
                return "";
            }
        }
    }